<template>
    <view class="container">
        <view class="">
            <view class="head-box row">
                <view :class="['head-state-btn', projectType == 0 ? 'head-state-btn-active' : '']"
                    @click="onSetProjectType(0)">
                    日日保
                </view>
                <view :class="['head-state-btn', projectType == 1 ? 'head-state-btn-active' : '']"
                    @click="onSetProjectType(1)">
                    长期保
                </view>
            </view>
        </view>
        <view class="head">
            <view class="info-box">
                <view class="title">
                    选择公司：
                </view>
                <view class="input-box row" @click="choosecompany">
                    <div :class="{ input: true, dark: companyName != '' }">{{ companyName === '' ? '点击选择客户劳务公司' :
                        companyName }}
                    </div>
                    <img class="more-img" src="@/static/score/more.png" alt="" />
                </view>
                <!-- <div>
                    <picker mode="date" :value="month" fields="month" @change="bindDateChange">
                        <view class="uni-input">{{ month !== '' ? month : '请选择时间' }}</view>
                    </picker>
                </div> -->
                <view class="title">
                    选择时间区间：
                </view>
                <view class="input-box row">
                    <uni-datetime-picker :start="mindate" :end="maxdate" @change="changedate" v-model="date"
                        type="daterange" rangeSeparator="至" :border="false" :clear-icon="false" />
                    <img class="more-img" src="@/static/score/more.png" alt="" />
                </view>
                <view class="title">
                    选择保司：
                </view>
                <view class="input-box row" @click="toggle('top')">
                    <div :class="{ input: true, dark: insurecompany != '' }">{{ insurecompany === '' ? '请选择保司' :
                        insurecompany }}
                    </div>
                    <img class="more-img" src="@/static/score/more.png" alt="" />
                </view>
            </view>
        </view>
        <uni-popup ref="popup" background-color="rgba(0,0,0,0)">
            <view class="popup-content" :class="{ 'popup-height': types === 'left' || types === 'right' }">
                <scroll-view scroll-y="true" style="height: 465rpx;border-bottom-left-radius: 16rpx;
    border-bottom-right-radius: 16rpx;;" bindscrolltoupper="upper" bindscrolltolower="lower" bindscroll="scroll"
                    scroll-into-view="{{toView}}" scroll-top="{{scrollTop}}">
                    <div class="top">选择保司</div>
                    <div v-show="projectType === 0">
                        <div class="listitem" v-for="(ele, index) in insurecompanylist" :key="index"
                            @click="changechoose(index, ele.name, ele.insureCompanyType, ele.planCodes)">
                            <div class="company">{{ ele.name }}</div>
                            <div class="imgbox" v-show="insurecompanyflag === index"><img class="img"
                                    src="@/static/selected.png" alt=""></div>
                        </div>
                    </div>
                    <div v-show="projectType === 1">
                        <div class="listitem" v-for="(ele, index) in insurecompanylist" :key="index"
                            @click="changechoose(index, ele.dictLabel, ele.dictValue, [])">
                            <div class="company">{{ ele.dictLabel }}</div>
                            <div class="imgbox" v-show="insurecompanyflag === index"><img class="img"
                                    src="@/static/selected.png" alt=""></div>
                        </div>
                    </div>
                </scroll-view>
            </view>
        </uni-popup>
    </view>
    <view class="btnbox" @click="nextstep">
        <view class="btn">下一步</view>
    </view>
</template>
<script setup lang="ts" >
import { getlongHojiapi, getdayHojiapi } from '@/api/insureProve'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getCurrentInstance, onMounted, ref, watch, watchEffect } from 'vue'
import { newContacts, getEnterpriseName } from '@/api/contact'
import user from '@/utils/user'
import { shake } from '@/utils/util'
import { companyNameAuto } from '@/api/base'
import dayjs from 'dayjs'
const projectType = ref(0)
const tipList = ref<any>([])
const isTips = ref(false)
const tipId = ref()
const enterprise = ref('')
const cstContactId = ref('')
const pageNum = ref(1)
const pageSize = ref(50)
const isNextPage = ref(true)
const date = ref([])
const month = ref('')
const popup = ref()
const bindDateChange = (e) => {
    console.log(e)
    month.value = e.detail.value
}
const maxdate = ref('')
const mindate = ref('')
onMounted(() => {
    // let y = new Date().getFullYear()
    // let m = new Date().getMonth()
    // let cm = new Date().getMonth() + 1
    // let days = new Date(y, m + 1, 0).getDate()
    // mindate.value = `${y}-${m >= 10 ? m : '0' + m}-01`
    // maxdate.value = `${y}-${cm >= 10 ? cm : '0' + cm}-${days}`

    mindate.value = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')
    maxdate.value = dayjs().endOf('month').format('YYYY-MM-DD')
    console.log(111, mindate.value)
    console.log(222, maxdate.value)

    currentInstance.value = getCurrentInstance()
})
const insurecompanyflag = ref(-1)
const changechoose = (i: number, name: string, code: string, plan: any) => {
    console.log(code, 'codecodecodecodecode')
    // if (code === 'period_003_yg') {
    //     uni.showToast({
    //         title: "该保险暂不支持导出在保证明",
    //         icon: "none"
    //     })
    //     return
    // }
    insurecompanyflag.value = i
    insurecompany.value = name
    insurecompanycode.value = code
    planarr.value = plan
    popup.value.close()
    // currentInstance.value.ctx.$refs.popup.close()
}
const planarr = ref([])
const insurecompany = ref('')
const insurecompanycode = ref('')
const changedate = (e: any) => {
    insurecompanycode.value = ''
    insurecompany.value = ''
    insurecompanyflag.value = -1
    planarr.value = []
    date.value = e
    const datestart = e[0].split('-')
    const dateend = e[1].split('-')
    if (datestart[0] * 1 !== dateend[0] * 1 || datestart[1] * 1 !== dateend[1] * 1) {
        uni.showToast({
            title: "时间不能跨月选择!",
            icon: "none"
        })
        iskm.value = true
        console.log(date.value, '1111')
    } else {
        iskm.value = false
        console.log(date.value, '1111')
    }
}
const iskm = ref(false)

const companyid = ref('')
onShow(() => {
    insurecompanycode.value = ''
    insurecompany.value = ''
    insurecompanyflag.value = -1
    planarr.value = []
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1] // 当前页的实例
    console.log(currPage.$vm.value)
    if (currPage.$vm.value) {
        companyid.value = currPage.$vm.value.id
        companyName.value = currPage.$vm.value.name
    }
})
const companyName = ref('')
const insurecompanylist = ref()
const currentInstance = ref<any>('')
const types = ref('center')
const toggle = async (type: any) => {
    console.log(date.value, '2213323232')
    const arr = date.value
    if (companyName.value === '') {
        uni.showToast({
            title: "请先选择公司",
            icon: "none"
        })
    } else if (date.value.length == 0) {
        uni.showToast({
            title: "请选择时间",
            icon: "none"
        })
    } else if (iskm.value) {
        uni.showToast({
            title: "时间不能跨月选择,请重新选择",
            icon: "none"
        })
    } else {
        if (projectType.value === 0) {
            const res = await getdayHojiapi({
                type: 1,
                companyId: companyid.value,
                startTime: arr[0],
                endTime: arr[1]
            })
            insurecompanylist.value = res
            types.value = type
            popup.value.open(type)
            // currentInstance.value.ctx.$refs.popup.open(type)
        } else {
            console.log(2)
            const res = await getlongHojiapi()
            insurecompanylist.value = res
            types.value = type
            popup.value.open(type)
            // currentInstance.value.ctx.$refs.popup.open(type)
        }
    }
}
const choosecompany = () => {
    uni.navigateTo({
        url: "/packageInsureProve/pages/choosecompany/index?type=" + projectType.value
    })
}
const onScroll = async () => {
    if (!isNextPage.value) {
        return
    }
    pageNum.value += 1
    await getEnterprise()
}
// 切换头部tab
const onSetProjectType = async (event: number) => {
    projectType.value = event
    companyid.value = ''
    companyName.value = ''
    date.value = []
    insurecompanycode.value = ''
    insurecompany.value = ''
    insurecompanyflag.value = -1
    planarr.value = []
}

const onEnterprise = async () => {
    shake(async () => {
        pageNum.value = 1
        isNextPage.value = true
        tipList.value = []
        if (enterprise.value) {
            isTips.value = true
            await getEnterprise()
        } else {
            isTips.value = false
            await getEnterprise()
        }
        console.log(enterprise.value, 'enterprise')
    })
}
const onTip = async (id: string, name: string) => {
    enterprise.value = name
    tipId.value = id
    isTips.value = false
}
const getEnterprise = async () => {
    const result = await getEnterpriseName({
        companyName: enterprise.value,
        pageSize: pageSize.value,
        pageNum: pageNum.value
    })
    console.log(result, 'result')
    if (!result.hasNextPage) {
        isNextPage.value = false
    }
    const arr = []
    arr.push(...tipList.value)
    arr.push(...result.list)
    tipList.value = arr as any
}
// 下一步
const nextstep = () => {
    if (companyid.value === '') {
        uni.showToast({
            title: '请选择公司',
            icon: 'none'
        })
    } else if (date.value.length === 0) {
        uni.showToast({
            title: '请选择时间',
            icon: 'none'
        })
    } else if (insurecompanycode.value === '') {
        uni.showToast({
            title: '请选择保司',
            icon: 'none'
        })
    } else {
        let cdate = []
        const datestart = date.value[0].split('-')
        const day = getMonthDay(datestart[0] * 1, datestart[1] * 1)
        cdate = [datestart[0] + '-' + datestart[1] + '-' + '01', datestart[0] + '-' + datestart[1] + '-' + day]
        console.log(cdate)
        const info = {
            type: projectType.value === 0 ? '日日保' : '长期保',
            companyid: companyid.value,
            companyName: companyName.value,
            timearr: projectType.value === 0 ? date.value : cdate,
            insurecompanycode: insurecompanycode.value,
            insurecompany: insurecompany.value,
            planarr: planarr.value
        }
        console.log(info)
        uni.navigateTo({
            url: "/packageInsureProve/pages/insureProvedetail/index?info=" + encodeURIComponent(JSON.stringify(info))
        })
    }
}
const getMonthDay = (year: any, month: any) => {
    const days = new Date(year, month, 0).getDate()
    return days
}

</script>
<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background-color: #FAFAFC;
    padding: 18rpx;
    box-sizing: border-box;
}

.head-box {
    width: 100%;
    background: #F4F4F7;
    border-radius: 16rpx;
    height: 88rpx;
    border-radius: 50rpx;
}

.head-state-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    height: 88rpx;
    color: #565868;
    background-color: #F4F4F7;
    font-size: 28rpx;
    border-radius: 50rpx;
}

.head-state-btn-active {
    background: $green;
    color: #202536;
    font-weight: 600;
    font-size: 32rpx;
    background-color: #FFFFFF;
    font-weight: bold;
    border-radius: 50rpx;
}

.info-box {
    margin-top: 32rpx;
    padding: 32rpx;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 16rpx;

    .title {
        color: #565868;
        font-size: 28rpx;
        font-weight: normal;
    }

    .input-box {
        min-height: 88rpx;
        display: flex;
        align-items: center;
        border-bottom: 1rpx solid rgba(#9497B1, 0.1);
        margin-bottom: 29rpx;

        .input {
            font-size: 32rpx;
            color: #9497B1;
            border: none;
            padding-left: 2rpx;
            margin-top: 0rpx;
        }

        .more-img {
            width: 50rpx;
            height: 35rpx;
        }

        .textarea-input {
            width: 100%;
            margin-top: 24rpx;
            padding: 30rpx 24rpx;
            background: #F4F4F7;
            border-radius: 8rpx;
            font-size: 28rpx;
        }
    }
}

.scroll-box {
    max-height: 60vw;
}

.btnbox {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    height: 167rpx;
    background-color: #FFFFFF;
    padding: 12rpx 30rpx;

    .btn {
        box-sizing: border-box;
        height: 90rpx;
        line-height: 90rpx;
        text-align: center;
        background-color: #3E5FF5;
        border-radius: 44rpx 44rpx 44rpx 44rpx;
        color: #FFFFFF;
        font-size: 32rpx;
    }
}

.popup-content {
    background-color: #ffffff;
    width: 100%;
    box-sizing: border-box;
    padding: 60rpx 60rpx 30rpx 60rpx;
    max-height: 465;
    overflow-y: scroll;
    border-bottom-left-radius: 16rpx;
    border-bottom-right-radius: 16rpx;

    .top {
        font-size: 32rpx;
        color: #202536;
        font-weight: 700;
    }

    .listitem {
        display: flex;
        align-items: center;
        height: 88rpx;
        justify-content: space-between;

        .imgbox {
            width: 32rpx;
            height: 32rpx;

            .img {
                width: 100%;
                height: 100%;
            }
        }

        .company {
            color: #565868;
            font-size: 28rpx;
        }
    }
}

.dark {
    color: #202536 !important;
}
</style>
